package db;
import java.awt.EventQueue;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

import com.mysql.jdbc.DatabaseMetaData;


public class DBconnector {
	private Connection connect = null;
	  public Statement statement = null;
	  private PreparedStatement preparedStatement = null;
	  public ResultSet resultSet = null;
	  private DBui ui;
	  DBconnector(DBui ui){
		  this.ui=ui;
		  try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			JOptionPane.showMessageDialog(new JFrame(), e.getLocalizedMessage());
		}
	  }
	  public void connect(String user,String pw){
		  try {
			connect = DriverManager
			          .getConnection("jdbc:mysql://localhost/muzyka?"
			              + "user="+user+"&password="+pw);
			statement = connect.createStatement();
			Meta();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			JOptionPane.showMessageDialog(new JFrame(), e.getLocalizedMessage());
		}
		  
	  }
	  public void querry(String ask){
		  try {
			  ui.clearTable();
			resultSet = statement.executeQuery("Call "+ask+"()");
			setColumns();
			Vector<String> v;
			while(resultSet.next()){
				v=new Vector();
				 for(int i=1;i<=resultSet.getMetaData().getColumnCount();i++){
					 
		    		  v.add(resultSet.getString(i));
		    		  
		    	  }
				 ui.addRow(v);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			JOptionPane.showMessageDialog(new JFrame(), e.getLocalizedMessage());
		} 
		  
	  }
	  public void setColumns(){
		  try {
			for  (int i = 1; i<= resultSet.getMetaData().getColumnCount(); i++){
			     	ui.addColumn(resultSet.getMetaData().getColumnName(i));
			    }
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			JOptionPane.showMessageDialog(new JFrame(), e.getLocalizedMessage());
		}
	  }
	  public void insert(String s){
		  try {
			s="call insert"+s;
			System.out.println(s);
			statement.executeUpdate(s);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			JOptionPane.showMessageDialog(new JFrame(), e.getLocalizedMessage());
		}
	  }
	  public void Meta(){
		  try {
			  
			DatabaseMetaData md = (DatabaseMetaData) connect.getMetaData();
			resultSet=md.getTables(null, null, "%", null);
			while(resultSet.next()){
				ui.addTable(resultSet.getString(3));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			JOptionPane.showMessageDialog(new JFrame(), e.getLocalizedMessage());
		}
	  }


	

	

}
